package com.bsth.controller;

import com.bsth.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping(value="/users")
public class UserController {
	//创建线程安全的Map
	private Map<Long,User> users = Collections.synchronizedMap(new HashMap<Long, User>());

	/**
	 * 获取用户列表,可以通过添加@RequestParam从页面中传递参数查询分页数据
	 * @return
	 */
	@GetMapping("/")
	public List<User> getUsers() {
		List<User> list = new ArrayList<>(users.values());
		return list;
	}

	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@PostMapping("/")
	public String addUser(@ModelAttribute User user) {
		users.put(user.getId(),user);
		return "Success";
	}

	/**
	 * 根据ID查询用户
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public User getUser(@PathVariable Long id){
		return users.get(id);
	}

	/**
	 * 更新用户信息
	 * @param id
	 * @param user
	 * @return
	 */
	@PutMapping("/{id}")
	public String updateUser(@PathVariable Long id,@ModelAttribute User user) {
		User u = users.get(user.getId());
		u.setName(user.getName());
		u.setAge(user.getAge());
		users.put(u.getId(),u);
		return "Success";
	}

	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	public String deleteUser(@PathVariable Long id) {
		users.remove(id);
		return "Success";
	}
}
